package com.sojson.util.encrypt.oneway.alike.hmacsha256;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.sojson.util.encrypt.enums.EEncryptType;

/**
 * HMAC-SHA256单向加密工具类
 * 
 * @author liu
 * @date 2020-09-04
 */
public class Hmacsha256Util {

    /**
     * 加密
     * 
     * @param data  内容
     * @param key   密钥
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String key) throws Exception {
        return encryptToStr(data.getBytes(), key);
    }

    /**
     * 加密
     * 
     * @param data  内容
     * @param key   密钥
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data, String key) throws Exception {
        return encryptToStr(data, key).getBytes();
    }

    /**
     * 加密
     * 
     * @param data  内容
     * @param key   密钥
     * @return
     * @throws Exception
     */
    public static byte[] encryptToByte(String data, String key) throws Exception {
        return encrypt(data.getBytes(), key);
    }

    /**
     * 加密
     * 
     * @param data  内容
     * @param key   密钥
     * @return
     * @throws Exception
     */
    public static String encryptToStr(byte[] data, String key) throws Exception {
        return encrypt(data, key.getBytes());
    }

    /**
     * 加密
     * 
     * @param data  内容
     * @param key   密钥
     * @return
     * @throws Exception
     */
    public static String encrypt(byte[] data, byte[] key) throws Exception {
        String type = EEncryptType.HMACS_HA256.getType();
        Mac sha256_HMAC = Mac.getInstance(type);
        SecretKeySpec secret_key = new SecretKeySpec(key, type);
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data);
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString();
    }

    /**
     * 加密并转为大写
     * 
     * @param data  内容
     * @param key   密钥
     * @return
     * @throws Exception
     */
    public static String encryptToUpperCase(String data, String key) throws Exception {
        return encrypt(data, key).toUpperCase();
    }

    /**
     * 加密并转为大写
     * 
     * @param data  内容
     * @param key   密钥
     * @return
     * @throws Exception
     */
    public static String encryptToUpperCase(byte[] data, byte[] key) throws Exception {
        return encrypt(data, key).toUpperCase();
    }

}